package com.example.handsets8app.View;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;

import com.example.handsets8app.Base.BaseActivity;

import com.example.handsets8app.Base.BaseConfig;
import com.example.handsets8app.Bean.JJHhandSetRequestBean;
import com.example.handsets8app.Bean.RzSelectListRequsetBean;
import com.example.handsets8app.Bean.RzSelectListResultBean;
import com.example.handsets8app.Bean.RzfindTimeControlListRequestBean;
import com.example.handsets8app.Bean.RzfindTimeControlListResultBean;
import com.example.handsets8app.Bean.RzhandSetResultBean;
import com.example.handsets8app.Customer.InputInformation;
import com.example.handsets8app.R;
import com.example.handsets8app.RetrufitHelp.BaseSubscriber;
import com.example.handsets8app.RetrufitHelp.ExceptionHandle;
import com.example.handsets8app.RetrufitHelp.RetrofitClient;
import com.example.handsets8app.Utils.DialogTipShow;
import com.example.handsets8app.Utils.IDCardUtils;
import com.example.handsets8app.Utils.LogUtil;
import com.example.handsets8app.Utils.SPUtil;
import com.example.handsets8app.Utils.StringUtil;
import com.example.handsets8app.Utils.TimeUtil;
import com.example.handsets8app.Utils.ToastUtil;
import com.example.handsets8app.Utils.VoiceUtils;
import com.example.handsets8app.Utils.util;
import com.synjones.idcard.IDCard;
import com.synjones.idcard.IDCardReaderRetInfo;
import com.synjones.reader.IDCardReaderModule;

import java.util.ArrayList;
import java.util.List;

public class OrderRzScienceActivity extends BaseActivity {

    private LinearLayout back;
    private InputInformation productName;
    private InputInformation productTime;
    private EditText peopleName;
    private EditText IdNumber;
    private Button btOrder;

    // 底部弹出框
    private OptionsPickerView pvNoLinkOptionsfirst, pvNoLinkOptionsecond;
    private RzSelectListRequsetBean rzSelectBean;
    private List<String> productNameList;
    private List<RzSelectListResultBean.DataBean> productDateList;
    private Long scenicTicketId;


    private RzfindTimeControlListRequestBean rzfindTimeControlListRequestBean;
    private List<String> timeList;
    private List<RzfindTimeControlListResultBean.DataBean.TimeControlListBean> timeDateList;
    private Long timeControlId;
    private Long projectId;

    // 订单支付
    private JJHhandSetRequestBean requsetBean;
    private List<JJHhandSetRequestBean.ProductParamListBean> listBeanList;
    private List<JJHhandSetRequestBean.ProductParamListBean.CertificateParamListBean> listBeanListIn;
    private List<JJHhandSetRequestBean.ProductParamListBean.TimeControlParamListBean> timeControlParamListBeanList;
    private JJHhandSetRequestBean.ProductParamListBean listBean;

    private String gateNo;

    //  身份证 引入
    public IDCardReaderModule idCardReaderModule;
    private ReadCardThread ReadCardThreadhandler;
    private boolean reading = false;
    private long StartTime = 0;
    boolean boolReadFringerprint = false;
    private String status = "";
    private static final int ReadOnceDone = 0x01;
    private static final int UpDateTime = 0x04;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ReadOnceDone:
                    IDCard idCard = (IDCard) msg.obj;
                    if (idCard != null) {
                        peopleName.setText(idCard.getName());
                        IdNumber.setText(idCard.getIDCardNo());
                    }
                    break;
            }
        }
    };
    private Button idScan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }



    private void sendOrder() {

        //判断输入是否正确
        if (StringUtil.isNullOrEmpty(peopleName.getText().toString().trim())) {
            VoiceUtils.getInstance().PlayAudioFile("请先输入姓名");
            return;
        }

        if (StringUtil.isNullOrEmpty(String.valueOf(projectId))) {
            VoiceUtils.getInstance().PlayAudioFile("请选择产品和时段");
            return;
        }
        if (StringUtil.isNullOrEmpty(String.valueOf(scenicTicketId))) {
            VoiceUtils.getInstance().PlayAudioFile("请选择产品和时段");
            return;
        }
        if (StringUtil.isNullOrEmpty(String.valueOf(timeControlId))) {
            VoiceUtils.getInstance().PlayAudioFile("请选择产品和时段");
            return;
        }

        if (!IDCardUtils.validateCard(IdNumber.getText().toString().trim())) {
            VoiceUtils.getInstance().PlayAudioFile("请输入有效证件号");
            return;
        }


        // 数据添加
        JJHhandSetRequestBean.ProductParamListBean.CertificateParamListBean bean = new JJHhandSetRequestBean.ProductParamListBean.CertificateParamListBean();
        bean.setCertificateName(peopleName.getText().toString().trim());
        bean.setCertificateNo(IdNumber.getText().toString().trim());
        bean.setCertificateTypeId(1);
        listBeanListIn.add(bean);
        listBean.setCertificateParamList(listBeanListIn);

        JJHhandSetRequestBean.ProductParamListBean.TimeControlParamListBean timeBean = new JJHhandSetRequestBean.ProductParamListBean.TimeControlParamListBean();
        timeBean.setOrdTimeControlId(timeControlId);
        timeBean.setProjectId(projectId);
        timeControlParamListBeanList.add(timeBean);
        listBean.setTimeControlParamList(timeControlParamListBeanList);
        listBean.setScenicTicketId(scenicTicketId);
        listBean.setArriveDT(TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_DATE_EN));
        listBean.setCustomerDiscountType(1);
        listBean.setSaleSum(1);
        listBeanList.add(listBean);


        requsetBean.setProductParamList(listBeanList);

        gateNo = (String) SPUtil.get(OrderRzScienceActivity.this, BaseConfig.JJH_CHECK_GATENO, "");
        if (StringUtil.isNullOrEmpty(gateNo)) {
            ToastUtil.showToast("请先进行设备绑定");
            return;
        }
        iosLoadDialog.show();
        RetrofitClient.getInstance(OrderRzScienceActivity.this, BaseUrl, headers).RZhandSetReserveProduct(requsetBean, new BaseSubscriber<RzhandSetResultBean>(OrderRzScienceActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                VoiceUtils.getInstance().PlayAudioFile(e.message);
                DialogTipShow.getInstance().ShowDialog(OrderRzScienceActivity.this, e.message);
                iosLoadDialog.dismiss();
            }

            @Override
            public void onNext(RzhandSetResultBean jjHhandSetResultBean) {
                if (jjHhandSetResultBean.getCode().equals("52007")) {
                    VoiceUtils.getInstance().PlayAudioFile(jjHhandSetResultBean.getMessage());
                    cleanFace();
                    DialogTipShow.getInstance().ShowDialogSuccess(OrderRzScienceActivity.this, jjHhandSetResultBean.getMessage());
                } else {
                    VoiceUtils.getInstance().PlayAudioFile(jjHhandSetResultBean.getMessage());
                    DialogTipShow.getInstance().ShowDialog(OrderRzScienceActivity.this, jjHhandSetResultBean.getMessage());
                }
                iosLoadDialog.dismiss();
            }
        });

    }

    private void cleanFace() {
        productName.setEditName("");
        productTime.setEditName("");
        peopleName.setText("");
        IdNumber.setText("");
    }

    private void getTimeSelset() {
        rzfindTimeControlListRequestBean.setScenicTicketId(String.valueOf(scenicTicketId));
        rzfindTimeControlListRequestBean.setSaleChannelType("12");
        rzfindTimeControlListRequestBean.setControlDate(TimeUtil.getLocationTimeNew(TimeUtil.FORMAT_DATE_EN));
        RetrofitClient.getInstance(OrderRzScienceActivity.this, BaseUrl, headers).RzfindTimeControlListByScenicTicket(rzfindTimeControlListRequestBean, new BaseSubscriber<RzfindTimeControlListResultBean>(OrderRzScienceActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                VoiceUtils.getInstance().PlayAudioFile(e.message);
            }

            @Override
            public void onNext(RzfindTimeControlListResultBean rzfindTimeControlListResultBean) {
                if (rzfindTimeControlListResultBean.getCode().equals("200")) {
                    //返回成功 去做其他操作
                    projectId = rzfindTimeControlListResultBean.getData().get(0).getProjectId();
                    timeList.clear();
                    timeDateList.clear();
                    for (int i = 0; i < rzfindTimeControlListResultBean.getData().size(); i++) {
                        for (int i1 = 0; i1 < rzfindTimeControlListResultBean.getData().get(i).getTimeControlList().size(); i1++) {
                            timeList.add(rzfindTimeControlListResultBean.getData().get(i).getTimeControlList().get(i1).getControlStartTime() + "--" + rzfindTimeControlListResultBean.getData().get(i).getTimeControlList().get(i1).getControlEndTime()
                                    + "  " + rzfindTimeControlListResultBean.getData().get(i).getTimeControlList().get(i1).getResidueSum());
                            timeDateList.add(rzfindTimeControlListResultBean.getData().get(i).getTimeControlList().get(i1));
                        }
                    }
                    // 然后去显示
                    pvNoLinkOptionsecond.show();
                } else {
                    VoiceUtils.getInstance().PlayAudioFile(rzfindTimeControlListResultBean.getMessage());
                }
            }
        });
    }

    private void getProductName() {

        RetrofitClient.getInstance(OrderRzScienceActivity.this, BaseUrl, headers).RzfindScenicTicketSelectList(rzSelectBean, new BaseSubscriber<RzSelectListResultBean>(OrderRzScienceActivity.this) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                VoiceUtils.getInstance().PlayAudioFile(e.message);
            }

            @Override
            public void onNext(RzSelectListResultBean rzSelectListResultBean) {
                if (rzSelectListResultBean.getCode().equals("200")) {
                    //返回200 表示成功
                    productNameList.clear();
                    productDateList.clear();
                    for (int i = 0; i < rzSelectListResultBean.getData().size(); i++) {
                        productNameList.add(rzSelectListResultBean.getData().get(i).getScenicTicketName());
                        productDateList.add(rzSelectListResultBean.getData().get(i));
                    }
                    //添加好后 ，就去显示底部
                    pvNoLinkOptionsfirst.show();
                } else {
                    VoiceUtils.getInstance().PlayAudioFile(rzSelectListResultBean.getMessage());
                }
            }
        });

    }

    @Override
    protected void initView() {

        back = (LinearLayout) findViewById(R.id.ll_title_back);
        productName = (InputInformation) findViewById(R.id.if_rz_product_name);
        productTime = (InputInformation) findViewById(R.id.if_rz_time);
        peopleName = (EditText) findViewById(R.id.if_rz_people_name);
        IdNumber = (EditText) findViewById(R.id.if_rz_id);
        btOrder = (Button) findViewById(R.id.bt_order);
        idScan = (Button) findViewById(R.id.bt_scan_id);

        //数据准备
        if (rzSelectBean == null) {
            rzSelectBean = new RzSelectListRequsetBean();

        }
        if (rzfindTimeControlListRequestBean == null) {
            rzfindTimeControlListRequestBean = new RzfindTimeControlListRequestBean();
        }

        if (productNameList == null) {
            productNameList = new ArrayList<>();
        }

        if (productDateList == null) {
            productDateList = new ArrayList<>();
        }

        if (timeList == null) {
            timeList = new ArrayList<>();
        }

        if (timeDateList == null) {
            timeDateList = new ArrayList<>();
        }

        initNoLinkOptionsPicker();
        initNoLinkOptionsPickerSecond();

        // 支付数据
        if (requsetBean == null) {
            requsetBean = new JJHhandSetRequestBean();
        }
        requsetBean.setSaleChannelType(12);
        if (listBeanList == null) {
            listBeanList = new ArrayList<>();
        }

        if (listBeanListIn == null) {
            listBeanListIn = new ArrayList<>();
        }

        if (timeControlParamListBeanList == null) {
            timeControlParamListBeanList = new ArrayList<>();
        }
        if (listBean == null) {
            listBean = new JJHhandSetRequestBean.ProductParamListBean();
        }

        cleanFace();
        VoiceUtils.init(OrderRzScienceActivity.this);

        // 引入 身份证 模块
        // 身份证 读取模块 初始化
        if (idCardReaderModule == null) {
            idCardReaderModule = IDCardReaderModule.getInstance(this);
        }


    }

    @Override
    protected void initData() {

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        productName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 产品名称选择
                // 点击 就 网络请求 一次
                getProductName();
            }
        });

        productTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 时段选择
                // 判断上面数据是否已经获取到了
                if (StringUtil.isNullOrEmpty(String.valueOf(scenicTicketId))) {
                    VoiceUtils.getInstance().PlayAudioFile("请先选择产品");
                    return;
                }
                getTimeSelset();
            }
        });

        btOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 由于价格都是 0 元，直接调创建订单即可完成支付
                sendOrder();

            }
        });

        idScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (reading) {
                    VoiceUtils.getInstance().PlayAudioFile("身份证扫描已打开，请勿重复操作");
                } else {
                    VoiceUtils.getInstance().PlayAudioFile("正在打开身份证扫描");
                    startReadThread();
                }

            }
        });
    }

    private void startReadThread() {
        reading = true;
        ReadCardThreadhandler = new ReadCardThread();
        ReadCardThreadhandler.start();
    }


    //读卡线程  新中新
//    class ReadCardThread extends Thread {
//        public void run() {
//            OpenReader();
//            long t = System.currentTimeMillis();
//            while (reading) {//读卡器上电需要时间，通过获取samvid判断读卡器是否已工作
//                String samvID = idCardReaderModule.getSamvIDString();
//                if (samvID != null && samvID.length() > 0)
//                    break;
//                util.sleep(50);//如果超时，则重新打开读卡器
//                if (System.currentTimeMillis() - t > 2000) {
//                    t = System.currentTimeMillis();
//                    idCardReaderModule.close();
//                    idCardReaderModule.open();
//                }
//            }
//
//            StartTime = System.currentTimeMillis();
//            UpdateTimerThread utt = new UpdateTimerThread();
//            utt.start();
//            while (reading) {
//                try {
//                    //getIDcardInfo()只读身份证信息，不读取指纹信息。 等同于getIDcardInfo(false, true, false);
//                    IDCardReaderRetInfo retInfo;
//                    if (!boolReadFringerprint)//是否需要读指纹
//                        retInfo = idCardReaderModule.getIDcardInfo();
//                    else
//                        retInfo = idCardReaderModule.getIDcardInfo(false, true, true);
//
//                    //读取指纹信息，读卡时间会稍长  可参考指纹的activity中读取身份证指纹按钮的实现
//                    //IDCardReaderRetInfo retInfo = idCardReaderModule.getIDcardInfo(boolSameCardReadOnce, boolDecodePhoto, boolReadFringerprint);
//                    //samvID=idCardReaderModule.getSamvIDString();//获取公安部二代证模块编号
//                    //String appendAddress=idCardReaderModule.getAppendAddress();//获取身份证内的追加地址信息
//                    if (retInfo.errCode == IDCardReaderRetInfo.ERROR_OK) {
//                        if (boolReadFringerprint)//仅测试时读取追加信息
//                            retInfo.card.setAppendAddress(idCardReaderModule.getAppendAddress());
//                        mHandler.obtainMessage(ReadOnceDone, retInfo.card).sendToTarget();
//                        status = "";
//                        Thread.sleep(500);
//                    } else {
//                        status = util.bytesToHexString(new byte[]{retInfo.sw1, retInfo.sw2, retInfo.sw3});
//                        mHandler.obtainMessage(ReadOnceDone, null).sendToTarget();
//                        Thread.sleep(200);
//                    }
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }//while
//
////            mHandler.obtainMessage(ReadThreadDone).sendToTarget();
//
//        }//run
//
//        public void StopRead() {
//            reading = false;
//            interrupted();
//            try {
//                join(500);
//            } catch (InterruptedException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
//
//    }

    //读卡线程
    class ReadCardThread extends Thread{
        public void run() {
            OpenReader();
            if(!idCardReaderModule.isOpen()){
                reading=false;
                idCardReaderModule.close();
                Log.e("ReadCardThread","读卡器打开失败");
            }
            new UpdateTimerThread().start();

            while(reading)
            {
                try{
                    //getIDcardInfo()只读身份证信息，不读取指纹信息。 等同于getIDcardInfo(false, true, false);
                    IDCardReaderRetInfo retInfo;
//                    if(!boolReadFringerprint)//是否需要读指纹
//                        retInfo = idCardReaderModule.getIDcardInfo();
//                    else
                        retInfo = idCardReaderModule.getIDcardInfo(false,false,false);

                    //读取指纹信息，读卡时间会稍长  可参考指纹的activity中读取身份证指纹按钮的实现
                    //IDCardReaderRetInfo retInfo = idCardReaderModule.getIDcardInfo(boolSameCardReadOnce, boolDecodePhoto, boolReadFringerprint);
                    //samvID=idCardReaderModule.getSamvIDString();//获取公安部二代证模块编号
                    //String appendAddress=idCardReaderModule.getAppendAddress();//获取身份证内的追加地址信息
                    if(retInfo.errCode==IDCardReaderRetInfo.ERROR_OK) {
                        //if(boolReadFringerprint)//仅测试时读取追加信息
                        //	retInfo.card.setAppendAddress(idCardReaderModule.getAppendAddress());
                        mHandler.obtainMessage(ReadOnceDone,retInfo.card).sendToTarget();
                        LogUtil.d(TimeUtil.getLocationTime() + "--" + retInfo.card.getIDCardNo());
                        status="";
                        Thread.sleep(500);
                    } else if(retInfo.errCode==IDCardReaderRetInfo.ERROR_RECV_FINDCARD){
                        Log.e("ReadCardThread","通信错误,重新打开读卡器");
                        idCardReaderModule.close();
                        Thread.sleep(3000);
                        idCardReaderModule.open();
                        if(!idCardReaderModule.isOpen()){
                            reading=false;
                            idCardReaderModule.close();
                            Log.e("ReadCardThread","读卡器打开失败");
                        }
                        LogUtil.d(TimeUtil.getLocationTime() + "--" + "读卡器打开失败");
                    } else{
                        status=util.bytesToHexString(new byte[]{retInfo.sw1,retInfo.sw2,retInfo.sw3});
                        mHandler.obtainMessage(ReadOnceDone,null).sendToTarget();
                        Thread.sleep(200);
                        LogUtil.d(TimeUtil.getLocationTime() + "--" + "未找到身份证");
                    }

                }catch (Exception e) {
                    e.printStackTrace();
                }
            }//while

//            mHandler.obtainMessage(ReadThreadDone).sendToTarget();

        }//run

        public void StopRead(){
            reading=false;
            interrupted();
        }

    }

    /**
     * 打开读卡器
     *
     * @Title OpenReader
     */
    private void OpenReader() {
        if (!idCardReaderModule.isOpen())
            idCardReaderModule.open();
    }

    /**
     * 关闭读卡器 身份证
     *
     * @Title CloseReader
     */
    private void CloseReader() {
        //停止读卡线程
        if (ReadCardThreadhandler != null) {
            ReadCardThreadhandler.StopRead();
            ReadCardThreadhandler = null;
        }
        if (idCardReaderModule != null) {
            idCardReaderModule.close();
        }
    }

    class UpdateTimerThread extends Thread {
        public void run() {
            while (reading) {
                mHandler.obtainMessage(UpDateTime).sendToTarget();
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public int initLayoutId() {
        return R.layout.activity_order_rz_science;
    }

    // 不联动的多级选项
    private void initNoLinkOptionsPicker() {
        pvNoLinkOptionsfirst = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
            }
        }).setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
            @Override
            public void onOptionsSelectChanged(int options1, int options2, int options3) {
                productName.setEditName(productNameList.get(options1));
                scenicTicketId = productDateList.get(options1).getScenicTicketId();
//                scenicSpotBusinessOrgId = pointList.get(options1).getScenicSpotBusinessOrgId();
//                scenicSpotBusinessOrgName = pointList.get(options1).getScenicSpotBusinessOrgShortName();
            }
        })
                .setItemVisibleCount(10)
//                 .setSelectOptions(0, 1, 1)
                .build();
        pvNoLinkOptionsfirst.setNPicker(productNameList, null, null);
        pvNoLinkOptionsfirst.setSelectOptions(0, 1, 1);
    }

    // 不联动的多级选项
    private void initNoLinkOptionsPickerSecond() {
        pvNoLinkOptionsecond = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
            }
        }).setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
            @Override
            public void onOptionsSelectChanged(int options1, int options2, int options3) {
                productTime.setEditName(timeList.get(options1));
                timeControlId = timeDateList.get(options1).getTimeControlId();
//                scenicSpotBusinessOrgId = pointList.get(options1).getScenicSpotBusinessOrgId();
//                scenicSpotBusinessOrgName = pointList.get(options1).getScenicSpotBusinessOrgShortName();
            }
        })
                .setItemVisibleCount(10)
//                 .setSelectOptions(0, 1, 1)
                .build();
        pvNoLinkOptionsecond.setNPicker(timeList, null, null);
        pvNoLinkOptionsecond.setSelectOptions(0, 1, 1);
    }

    @Override
    protected void onStop() {
        super.onStop();
        //程序页面看不见后 ，就停止读取
        CloseReader();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        VoiceUtils.getInstance().closeVoice();
        CloseReader();

    }
}
